1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
/*!
Linear and substructural typing

TODO: go back to linearity only based model, tag symbols
*/
use super::*;

/// Usage of a value
#[derive(Copy, Clone, Eq, PartialEq, Hash, Default)]
pub struct Usage {
    /// Whether this value has been *consumed*, and hence can no longer be used in an affine term
    pub consumed: bool,
    /// Whether this value has *not* been observed, and hence must be observed
    pub unobserved: bool,
}

impl PartialOrd for Usage {
    #[inline]
    fn partial_cmp(&self, other: &Usage) -> Option<Ordering> {
        self.const_cmp(*other)
    }
}

impl Debug for Usage {
    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        Display::fmt(self.into_str(), fmt)
    }
}

impl Usage {
    /// A usage which has been consumed, without being observed
    pub const CONSUMED: Usage = Usage {
        consumed: true,
        unobserved: true,
    };
    /// A value which has neither been consumed or observed
    pub const UNUSED: Usage = Usage {
        consumed: false,
        unobserved: true,
    };
    /// A value which has been consumed and observed
    pub const USED: Usage = Usage {
        consumed: true,
        unobserved: false,
    };
    /// A value which has been observed, but not consumed
    pub const OBSERVED: Usage = Usage {
        consumed: false,
        unobserved: false,
    };

    /// A list of all possible usages
    pub const USAGES: [Usage; 4] = [Self::CONSUMED, Self::UNUSED, Self::USED, Self::OBSERVED];

    /// Get a string representation of this usage
    #[inline]
    pub const fn into_str(self) -> &'static str {
        match self {
            Usage::CONSUMED => "Consumed",
            Usage::UNUSED => "Unused",
            Usage::USED => "Used",
            Usage::OBSERVED => "Observed",
        }
    }

    /// Check whether two usages are equal in a constant way
    #[inline]
    pub const fn const_eq(self, other: Usage) -> bool {
        self.consumed == other.consumed && self.unobserved == other.unobserved
    }

    /// Take the meet of two usages
    #[inline]
    pub const fn meet(self, other: Usage) -> Usage {
        Usage {
            consumed: self.consumed && other.consumed,
            unobserved: self.unobserved && other.unobserved,
        }
    }

    /// Take the join of two usages
    #[inline]
    pub const fn join(self, other: Usage) -> Usage {
        Usage {
            consumed: self.consumed || other.consumed,
            unobserved: self.unobserved || other.unobserved,
        }
    }

    /// Take the conjunction of two usages
    #[inline]
    pub const fn conj(self, other: Usage) -> Usage {
        Usage {
            consumed: self.consumed || other.consumed,
            unobserved: self.unobserved && other.unobserved,
        }
    }

    /// Take the separating conjunction of two usages
    #[inline]
    pub const fn sep_conj(self, other: Usage) -> Result<Usage, Error> {
        if self.consumed && other.consumed {
            Err(Error::DoubleUse(self, other))
        } else {
            Ok(self.conj(other))
        }
    }
    /// Compare two usages in a constant way
    #[inline]
    pub const fn const_cmp(self, other: Usage) -> Option<Ordering> {
        let consumed_cmp = bool_cmp(self.consumed, other.consumed);
        let unobserved_cmp = bool_cmp(self.unobserved, other.unobserved);
        lattice_ord(consumed_cmp, unobserved_cmp)
    }
    /// Get the minimal linearity for a given usage
    #[inline]
    pub const fn min_linearity(self) -> Linearity {
        Linearity {
            affine: self.consumed,
            relevant: self.unobserved,
        }
    }
    /// Get a code for this linearity
    #[inline]
    pub const fn code(self) -> u64 {
        ((self.consumed as u64) << 2) | ((self.unobserved as u64) << 3)
    }
}

impl BitAnd for Usage {
    type Output = Usage;
    #[inline]
    fn bitand(self, other: Usage) -> Usage {
        self.meet(other)
    }
}

impl BitOr for Usage {
    type Output = Usage;
    #[inline]
    fn bitor(self, other: Usage) -> Usage {
        self.join(other)
    }
}

impl BitAndAssign for Usage {
    fn bitand_assign(&mut self, other: Usage) {
        *self = *self & other
    }
}

impl BitOrAssign for Usage {
    fn bitor_assign(&mut self, other: Usage) {
        *self = *self | other
    }
}

impl Mul for Usage {
    type Output = Result<Usage, Error>;
    #[inline]
    fn mul(self, other: Usage) -> Result<Usage, Error> {
        self.sep_conj(other)
    }
}

/// Substructurality requirements on a value
#[derive(Copy, Clone, Eq, PartialEq, Hash, Default)]
pub struct Linearity {
    /// Whether this value is *affine*, i.e. can be used at most once in a concrete term
    pub affine: bool,
    /// Whether this value is *relevant*, i.e. must be used at least once in a concrete term
    pub relevant: bool,
}

impl PartialOrd for Linearity {
    #[inline]
    fn partial_cmp(&self, other: &Linearity) -> Option<Ordering> {
        self.const_cmp(*other)
    }
}

impl Debug for Linearity {
    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        Display::fmt(self.into_str(), fmt)
    }
}

impl Linearity {
    /// A linear value, which must be used exactly once in a concrete term containing it
    pub const LINEAR: Linearity = Linearity {
        affine: true,
        relevant: true,
    };
    /// A relevant value, which must be used at least once in a concrete term producing it
    pub const RELEVANT: Linearity = Linearity {
        affine: false,
        relevant: true,
    };
    /// An affine value, which may only be used once in a concrete term
    pub const AFFINE: Linearity = Linearity {
        affine: true,
        relevant: false,
    };
    /// An unrestricted, or "nonlinear," value
    pub const NONLINEAR: Linearity = Linearity {
        affine: false,
        relevant: false,
    };

    /// A list of all possible linearities
    pub const LINEARITIES: [Linearity; 4] =
        [Self::LINEAR, Self::RELEVANT, Self::AFFINE, Self::NONLINEAR];
    /// Check whether a linearity is nonlinear
    #[inline]
    pub const fn is_nonlinear(self) -> bool {
        !(self.affine || self.relevant)
    }
    /// Check whether two linearities are equal in a constant way
    #[inline]
    pub const fn const_eq(self, other: Linearity) -> bool {
        self.affine == other.affine && self.relevant == other.relevant
    }
    /// Compare two linearities in a constant way
    #[inline]
    pub const fn const_cmp(self, other: Linearity) -> Option<Ordering> {
        let affine_cmp = bool_cmp(self.affine, other.affine);
        let relevant_cmp = bool_cmp(self.relevant, other.relevant);
        lattice_ord(affine_cmp, relevant_cmp)
    }
    /// Take the meet of two linearities
    #[inline]
    pub const fn meet(self, other: Linearity) -> Linearity {
        Linearity {
            affine: self.affine && other.affine,
            relevant: self.relevant && other.relevant,
        }
    }
    /// Take the join of two linearities
    #[inline]
    pub const fn join(self, other: Linearity) -> Linearity {
        Linearity {
            affine: self.affine || other.affine,
            relevant: self.relevant || other.relevant,
        }
    }
    /// Get a string representation of this linearity
    #[inline]
    pub const fn into_str(self) -> &'static str {
        match self {
            Linearity::NONLINEAR => "Nonlinear",
            Linearity::AFFINE => "Affine",
            Linearity::RELEVANT => "Relevant",
            Linearity::LINEAR => "Linear",
        }
    }
    /// Get the maximum possible usage for a linearity
    #[inline]
    pub const fn max_usage(self) -> Usage {
        Usage {
            consumed: self.affine,
            unobserved: self.relevant,
        }
    }
}

impl BitAnd for Linearity {
    type Output = Linearity;
    #[inline]
    fn bitand(self, other: Linearity) -> Linearity {
        self.meet(other)
    }
}

impl BitOr for Linearity {
    type Output = Linearity;
    #[inline]
    fn bitor(self, other: Linearity) -> Linearity {
        self.join(other)
    }
}

impl BitAndAssign for Linearity {
    fn bitand_assign(&mut self, other: Linearity) {
        *self = *self & other
    }
}

impl BitOrAssign for Linearity {
    fn bitor_assign(&mut self, other: Linearity) {
        *self = *self | other
    }
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn max_usage_min_linearity() {
        for &usage in &Usage::USAGES {
            assert_eq!(usage.min_linearity().max_usage(), usage)
        }
        for &linearity in &Linearity::LINEARITIES {
            assert_eq!(linearity.max_usage().min_linearity(), linearity)
        }
    }
    #[test]
    fn usage_meet_join_conj_sep() {
        let o = Usage::OBSERVED;
        let u = Usage::USED;
        let n = Usage::UNUSED;
        let c = Usage::CONSUMED;
        let tuples = [
            (o, o, o, o, o, Some(o)),
            (o, u, o, u, u, Some(u)),
            (o, n, o, n, o, Some(o)),
            (o, c, o, c, u, Some(u)),
            (u, u, u, u, u, None),
            (u, n, o, c, u, Some(u)),
            (u, c, u, c, u, None),
            (n, n, n, n, n, Some(n)),
            (n, c, n, c, c, Some(c)),
            (c, c, c, c, c, None),
        ];
        for &(left, right, meet, join, conj, sep) in tuples.iter() {
            assert_eq!(left & right, meet, "{:?} & {:?} == {:?}", left, right, meet);
            assert_eq!(left | right, join, "{:?} | {:?} == {:?}", left, right, join);
            assert_eq!(
                left.conj(right),
                conj,
                "{:?}.conj({:?}) == {:?}",
                left,
                right,
                conj
            );
            assert_eq!(right & left, meet, "{:?} & {:?} == {:?}", right, left, meet);
            assert_eq!(right | left, join, "{:?} | {:?} == {:?}", right, left, join);
            assert_eq!(
                right.conj(left),
                conj,
                "{:?}.conj({:?}) == {:?}",
                right,
                left,
                conj
            );
            let lrsep = sep.ok_or(Error::DoubleUse(left, right));
            let rlsep = sep.ok_or(Error::DoubleUse(right, left));
            assert_eq!(
                left * right,
                lrsep,
                "{:?} * {:?} == {:?}",
                left,
                right,
                lrsep
            );
            assert_eq!(
                right * left,
                rlsep,
                "{:?} * {:?} == {:?}",
                right,
                left,
                rlsep
            );
        }
    }
    #[test]
    fn usage_partial_ord() {
        use Ordering::*;
        let o = Usage::OBSERVED;
        let u = Usage::USED;
        let n = Usage::UNUSED;
        let c = Usage::CONSUMED;
        let ords = [
            (o, o, Some(Equal)),
            (o, u, Some(Less)),
            (o, n, Some(Less)),
            (o, c, Some(Less)),
            (u, u, Some(Equal)),
            (u, n, None),
            (u, c, Some(Less)),
            (n, n, Some(Equal)),
            (n, c, Some(Less)),
            (c, c, Some(Equal)),
        ];
        for (left, right, ord) in ords.iter() {
            assert_eq!(
                left.partial_cmp(right),
                *ord,
                "{:?}.partial_cmp({:?})",
                left,
                right
            );
            assert_eq!(
                right.partial_cmp(left),
                ord.map(Ordering::reverse),
                "{:?}.partial_cmp({:?})",
                right,
                left
            );
        }
        for &left in &Usage::USAGES {
            for &right in &Usage::USAGES {
                assert!(left.meet(right) <= left);
                assert!(left.join(right) >= left);
            }
        }
    }
    #[test]
    fn linearity_meet_join() {
        let n = Linearity::NONLINEAR;
        let a = Linearity::AFFINE;
        let r = Linearity::RELEVANT;
        let l = Linearity::LINEAR;
        let tuples = [
            (n, n, n, n),
            (n, a, n, a),
            (n, r, n, r),
            (n, l, n, l),
            (a, a, a, a),
            (a, r, n, l),
            (a, l, a, l),
            (r, r, r, r),
            (r, l, r, l),
            (l, l, l, l),
        ];
        for &(left, right, meet, join) in tuples.iter() {
            assert_eq!(left & right, meet, "{:?} & {:?} == {:?}", left, right, meet);
            assert_eq!(right & left, meet, "{:?} & {:?} == {:?}", right, left, meet);
            assert_eq!(left | right, join, "{:?} | {:?} == {:?}", left, right, join);
            assert_eq!(right | left, join, "{:?} | {:?} == {:?}", right, left, join);
        }
    }
    #[test]
    fn linearity_partial_ord() {
        use Ordering::*;
        let n = Linearity::NONLINEAR;
        let a = Linearity::AFFINE;
        let r = Linearity::RELEVANT;
        let l = Linearity::LINEAR;
        let ords = [
            (n, n, Some(Equal)),
            (n, a, Some(Less)),
            (n, r, Some(Less)),
            (n, l, Some(Less)),
            (a, a, Some(Equal)),
            (a, r, None),
            (a, l, Some(Less)),
            (r, r, Some(Equal)),
            (r, l, Some(Less)),
            (l, l, Some(Equal)),
        ];
        for (left, right, ord) in ords.iter() {
            assert_eq!(
                left.partial_cmp(right),
                *ord,
                "{:?}.partial_cmp({:?})",
                left,
                right
            );
            assert_eq!(
                right.partial_cmp(left),
                ord.map(Ordering::reverse),
                "{:?}.partial_cmp({:?})",
                right,
                left
            );
        }
        for &left in &Linearity::LINEARITIES {
            for &right in &Linearity::LINEARITIES {
                assert!(left.meet(right) <= left);
                assert!(left.join(right) >= left);
            }
        }
    }
}